<?php

namespace app\controller;

use Tinywan\Storage\Storage;
use const support\ERROR;
use const support\OPERATE_ERROR;
use const support\PARAMETER_ERROR;

class UploadController
{

    //上传图片文件
    public function uploadPic(): \support\Response
    {
        $file = current(request()->file());
        if (!$file || !$file->isValid()) {
            return buildFail(PARAMETER_ERROR,'图片不能为空');
        }
        try {
            //获取base64图片资源
            $base64=sprintf('data:image/jpeg;base64,%s',base64_encode(file_get_contents($file->getPathname())));
            $response =Storage::disk(Storage::MODE_OSS, false)->uploadBase64($base64,$file->getUploadExtension());
            if (empty($response['url'])){
                return buildFail(OPERATE_ERROR,'图片上传失败');
            }
            return buildSuccess([
                'url'=>$response['url'],
                'size'=>$response['size'],
                'extension'=>$response['extension']
            ]);
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

}